package com.aeye.mbr.upms.client.interceptor;

import com.aeye.mbr.common.util.RedisUtil;
import org.apache.shiro.session.Session;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * <p>Description: 生成足够随机数的Token</p>
 *
 * @author zhouchuanbo
 * @version 1.0
 * @date 2018/3/28 0028
 */
public class CSRFTokenManager {
    /**
     * The token parameter name
     */
    static final String CSRF_PARAM_NAME = "CSRFToken";

    /**
     * The location on the session which stores the token
     */
    public static final  String CSRF_TOKEN_FOR_SESSION_ATTR_NAME = CSRFTokenManager.class
            .getName() + ".tokenval";

    public static String getTokenForSession(Session session) {
        String token = null;

        // I cannot allow more than one token on a session - in the case of two
        // requests trying to
        // init the token concurrently
        synchronized (session) {
            token =  RedisUtil.get(CSRF_TOKEN_FOR_SESSION_ATTR_NAME + "_" + session.getId());
            if (null == token) {
                token = UUID.randomUUID().toString();
                String aaa  = CSRF_TOKEN_FOR_SESSION_ATTR_NAME + "_" + session.getId();
                RedisUtil.set(CSRF_TOKEN_FOR_SESSION_ATTR_NAME + "_" + session.getId() , token, (int) session.getTimeout() / 1000);

            }
        }
        return token;
    }

    /**
     * Extracts the token value from the session
     *
     * @param request
     * @return
     */
    public static String getTokenFromRequest(HttpServletRequest request) {
        return request.getParameter(CSRF_PARAM_NAME);
    }

    private CSRFTokenManager() {
    };
}
